import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import type { Resource, ResourcesData } from '../types/resource'
import { StorageKey } from '../utils/enum'
import default_config from '../config/default_config'
import * as math from 'mathjs'
import { useGameStore } from './gameStore'
import { useLogStore } from './log'
import dayjs from 'dayjs'
import { getNumber } from '@/utils'

export const useResourcesStore = defineStore('resources', () => {
  const data = ref<ResourcesData>({})

  // 初始化
  const initData = async () => {
    let _data: ResourcesData = {}

    try {
      const localRs = await localStorage.getItem(StorageKey.RESOURCE_DATA)
      if (localRs) {
        _data = JSON.parse(localRs)
      } else {
        // @ts-ignore
        _data = default_config.resources
      }
      data.value = _data
    } catch (error) {
      console.error(error)
    }
  }

  // 更新
  const update = () => {
    if (!useGameStore().gameState.isRunning) {
      return
    }
    for (const key in data.value) {
      const _item = data.value[key] as Resource
      if (!_item.enabled) {
        continue
      }

      if (_item.details.value >= _item.details.max) {
        _item.details.value = _item.details.max
      } else {
        const _current = math.add(_item.details.value, _item.details.rate ?? 0)
        _current > _item.details.max
          ? (_item.details.value = _item.details.max)
          : (_item.details.value = _current)
      }
    }
  }

  // 修改数据
  const updateData = (id: string, key: string, value: any) => {
    const _item = data.value[id] as Resource
    if (_item) {
      if (key.includes('details')) {
        const _key = key.split('.')[1]
        // @ts-ignore
        _item.details[_key] = value
      } else {
        // @ts-ignore
        _item[key] = value
      }
    }
  }

  // 更新幸福点数
  const updateHappyPoint = (value: number) => {
    const current = getNumber(data.value.happinessPoints?.details.value)
    const _value = current + value
    updateData('happinessPoints', 'details.value', _value)
  }

  // 产出

  return {
    data,
    initData,
    update,
    updateData,
    updateHappyPoint,
  }
})
